#include "faultpre.hpp"

#include <utils.hpp>

namespace com
{
namespace otrd
{
#define DEFAULT_FAULT_PRE_FUNNEL    30
#define DEFAULT_FAULT_PRE_THRESHOLD 30000

FaultPreHandler::FaultPreHandler(const EepromItem& eepromItem,
                                 const EepromHandler& eepromHandler) :
    Handler(eepromItem, eepromHandler),
    FaultPreIface(utils::DBusHandler::getBus(),
                  utils::getEepromObjectPath(eepromItem.name).c_str())
{
    uint32_t FaultPreFunnel =
        (readFromEeprom(0, 1)[0] << 24) + (readFromEeprom(1, 1)[0] << 16) + 
        (readFromEeprom(2, 1)[0] << 8) + readFromEeprom(3, 1)[0];
    if (FaultPreFunnel == 0xFFFFFFFF)
    {
        FaultPreFunnel = DEFAULT_FAULT_PRE_FUNNEL;
    }

    uint32_t FaultPreThreshold = 
        (readFromEeprom(4, 1)[0] << 24) + (readFromEeprom(5, 1)[0] << 16) + 
        (readFromEeprom(6, 1)[0] << 8) + readFromEeprom(7, 1)[0];
    if (FaultPreThreshold == 0xFFFFFFFF)
    {
        FaultPreThreshold = DEFAULT_FAULT_PRE_THRESHOLD;
    }

    FaultPreIface::faultPreFunnel(FaultPreFunnel);
    FaultPreIface::faultPreThreshold(FaultPreThreshold);
}

uint32_t FaultPreHandler::faultPreFunnel(uint32_t value)
{
    if (value == FaultPreIface::faultPreFunnel())
    {
        return value;
    }

    writeToEeprom({static_cast<uint8_t>((value >> 24) & 0xFF), static_cast<uint8_t>((value >> 16) & 0xFF),static_cast<uint8_t>((value >> 8) & 0xFF),static_cast<uint8_t>(value & 0xFF)}, 0);
    FaultPreIface::faultPreFunnel(value);
    return value;
}

uint32_t FaultPreHandler::faultPreThreshold(uint32_t value)
{
    if (value == FaultPreIface::faultPreThreshold())
    {
        return value;
    }

    writeToEeprom({static_cast<uint8_t>((value >> 24) & 0xFF), static_cast<uint8_t>((value >> 16) & 0xFF),static_cast<uint8_t>((value >> 8) & 0xFF),static_cast<uint8_t>(value & 0xFF)}, 4);
    FaultPreIface::faultPreThreshold(value);
    return value;
}

} // namespace otrd
} // namespace com
